import CosSdk from 'cos-js-sdk-v5';
import request from '@/utils/request.js'
import Api from "@/utils/Api.js"
 // 生成一个符合 UUID v4 规范的随机值
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
export function txCosUpload(file,params,onProgress) {
	return new Promise(async (resolve, reject) => {
		const res = await request.sendRequest(Api.getPolicySign, params, "get")
		const {
			bucket,
			bucketBrowseHost,
			expiration,
			expiredTime,
			region,
			sessionToken,
			startTime,
			subdirectory,
			tmpSecretId,
			tmpSecretKey
		} = res.data.data
		const cos = new CosSdk({
			getAuthorization: function (options, callback) {
				callback({
					TmpSecretId: tmpSecretId,
					TmpSecretKey: tmpSecretKey,
					XCosSecurityToken: sessionToken,
					ExpiredTime: expiredTime,
					StartTime: startTime
				});
			}
		});
		// 凭借文件在cos中的存储路径
		const fileName = `${subdirectory}${generateUUID()}.${file.name.split('.').pop()}`
		// 上传文件
		cos.putObject({
			Bucket: bucket,
			Region: region,
			Key: fileName,
			Body: file,
			 StorageClass: 'STANDARD',
			onProgress: onProgress
		}, function (err, data) {
			if (err) {
				reject(err);
			} else {
				// 生成一个可访问的文件链接
				data.fileUrl = bucketBrowseHost ? (bucketBrowseHost + fileName) : (location.protocol + '//' + data.Location)
				resolve(data)
			}
		});
		return;
	})

}
